package com.netty.modbus.dto.request;

import com.netty.modbus.exception.DataConvertException;
import com.netty.modbus.util.CRC16;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * description: RequestBody <br>
 * date: 2021/10/8 14:59 <br>
 * @author: lwy <br>
 * version: 1.0 <br>
 */
public abstract class RequestBody {
    /**起始符*/
    private final byte[] start={123,123};
    /**结束符*/
    private final byte[] end= {125,125};
    /**命令字*/
    private final byte[] command={-112};


    public  RequestBody(){};


   /**
    * description: 编码
    * @version: 1.0
    * @date: 2021/10/8 17:02
    * @author: lwy
    * @return io.netty.buffer.ByteBuf
    */
    public abstract ByteBuf  encode() throws DataConvertException;

    /**
     * description: 通用编码
     * version: 1.0
     * date: 2021/10/8 17:02
     * @author: lwy
     * @param data 数据
     * @return io.netty.buffer.ByteBuf
     */
    public ByteBuf commEncode(byte[] data){
        ByteBuf buf = Unpooled.buffer();
        //起始符
        buf.writeBytes(this.start);
        //命令字
        buf.writeBytes(this.command);
        //modbus功能码及读取寄存器的
        buf.writeBytes(data);
        //modbus校验码
        byte [] modbusCrc16=CRC16.crc16(data);
        buf.writeBytes(modbusCrc16);
        //校验码生成
        ByteBuf verifyContent = Unpooled.buffer();
        verifyContent.writeBytes(this.command);
        verifyContent.writeBytes(data);
        verifyContent.writeBytes(modbusCrc16);
        byte[] verify=new byte[verifyContent.readableBytes()];
        verifyContent.readBytes(verify);
        buf.writeBytes(CRC16.crc16(verify));
        buf.writeBytes(this.end);
        return buf;
    }
}
